package PreparedStatement;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import com.neu.ceshi.Demo01;

public class Demo012 {
	private static String url = "jdbc:mysql://localhost:3306/mjq";
	private static String userName = "root";
	private static String pass = "mysql";
	private static String driver = "com.mysql.jdbc.Driver";
	public static Connection conn;
	public static PreparedStatement ps;
	static {
		try {
		//  驱动的加载   对应的方法是    Class.forName(driver);
			//  先生成下面的代码   然后快捷生成  try{}
			Class.forName(driver);
			//  生成    Connection 对象
			 conn=DriverManager.getConnection(url,userName,pass);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	} 
	/**
	 * 
	 * @param d
	 * @return
	 * @throws SQLException
	 *    
	 *    更新       的操作
	 * 
	 */
	public static boolean update(Demo01 d) throws SQLException {
		boolean flag = false;
		String sql = "update tb_user set username=?,address=?,email=? where id=?";
		//  生成执行器
		ps= conn.prepareStatement(sql);
		ps.setString(1, d.getCuername());
		ps.setString(2,d.getSddress());
		ps.setString(3,d.getEmile());
		ps.setInt(4,d.getId());
		int a = ps.executeUpdate();
		if(a>0) {
			flag = true;
		}
		return flag;
	}
	
	/**
	 * 
	 * @param args
	 * @throws SQLException
	 *  
	 *       查询     select 
	 */
	public static void findById(int id) throws SQLException {
		String sql = "select*from tb_user where id = ?";
		ps =  conn.prepareStatement(sql);
		ps.setInt(1, id);
		ResultSet rs = ps.executeQuery();
		if(rs.next()) {
			System.out.println(rs.getInt("id"));
		}
	}
	
	/**
	 * 
	 * @param args
	 * @throws SQLException
	 * 
	 *   增加       insert
	 */
	public static boolean insert(Demo01 d) throws SQLException {
		boolean flag = false;
		String sql = "insert into tb_user value(null,?,?,?)";
		ps= conn.prepareStatement(sql);
		ps.setString(1, d.getCuername());
		ps.setString(2,d.getSddress());
		ps.setString(3,d.getEmile());
		int a = ps.executeUpdate();
		if(a>0) {
			flag = true;
		}
		return flag;
	}
	/**
	 * 
	 * @param args
	 * @throws SQLException
	 * 
	 *   删除         delete 
	 */
	public static boolean delete(int b) throws SQLException {
		boolean flag = false;
		String sql ="delete from tb_user where id=?";
		ps= conn.prepareStatement(sql);
		ps.setInt(1,b);
		int a = ps.executeUpdate();
		if(a>0) {
			flag = true;
		}
		return flag;
	}
	
	public static void main(String[] args) throws SQLException {
		update(new Demo01(1,"哎呀我去","北京","www.11111.com"));
////		findById(7);
////		insert(new Demo01(0,"我爱你","美国","www.99999.com"));
//		delete(6);
	}
}
